package com.freewater.javabase.demo.mutithread.future;

import java.util.concurrent.*;

public class FutureDemo {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(4);
        // 定义任务:
        Callable<String> task = new Task("" + 1);
        // 提交任务并获得Future:
        Future<String> future = executor.submit(task);
        // 从Future获取异步执行返回的结果:
        try {
            String result = future.get();// 可能阻塞
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        executor.shutdown();
    }

    // 任务类
    static class Task implements Callable {

        private final String name;

        public Task(String name) {
            this.name = name;
        }

        @Override
        public String call() {
            System.out.println("start task " + name);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println("end task " + name);
            return "ok";
        }
    }
}
